package cn.virens;

import cn.hutool.setting.Setting;
import cn.virens.app.database.DatabaseExecutor;
import cn.virens.app.database.DatabaseManagerImpl;
import cn.virens.app.main.AppLoad;
import cn.virens.http.HttpServerImpl;
import cn.virens.packet.factory.LigthOffPacketFactory;
import cn.virens.packet.factory.LigthOnPacketFactory;
import cn.virens.support.TCPServerImplHeartbeat;

public class App extends AppLoad {
	private final static App app = new App();

	private HttpServerImpl mHttpServerManager = null;
	private DatabaseManagerImpl mDatabaseManager = null;
	private TCPServerImplHeartbeat mTcpServerManager = null;

	public static void main(String[] args) throws Exception {
		load(app);
	}

	@Override
	protected void start(Setting setting) {
		// --------数据库组件
		this.mDatabaseManager = register(new DatabaseManagerImpl());
		this.mDatabaseManager.setJdbcPassword(setting.getStr("jdbc.password"));
		this.mDatabaseManager.setJdbcUsername(setting.getStr("jdbc.username"));
		this.mDatabaseManager.setJdbcDriver(setting.getStr("jdbc.driver"));
		this.mDatabaseManager.setJdbcUrl(setting.getStr("jdbc.url"));

		// --------TCP Server组件
		this.mTcpServerManager = register(new TCPServerImplHeartbeat());
		this.mTcpServerManager.setHeartTimer(setting.getInt("tcp.heart.timer"));
		this.mTcpServerManager.setHeartidle(setting.getInt("tcp.heart.idle"));
		this.mTcpServerManager.setSelectTime(setting.getInt("tcp.select.timer"));
		this.mTcpServerManager.setPort(setting.getInt("tcp.port"));

		// 添加包构建器
		this.mTcpServerManager.addBuilder("ON_LIGHT", new LigthOnPacketFactory());
		this.mTcpServerManager.addBuilder("OFF_LIGHT", new LigthOffPacketFactory());

		// --------HTTP Server组件
		this.mHttpServerManager = register(new HttpServerImpl());
		this.mHttpServerManager.setConPackage("cn.virens.http.controller");
		this.mHttpServerManager.setPort(setting.getInt("http.port"));
	}

	private synchronized static App app() {
		return app;
	}

	/** 数据库管理器 */
	public static DatabaseExecutor db() {
		return app().mDatabaseManager;
	}

	/** 连接管理器 */
	public static TCPServer tcp() {
		return app().mTcpServerManager;
	}

	public static TCPServerDevice device() {
		return app().mTcpServerManager;
	}

	public static TCPServerHeartbeat packet() {
		return app().mTcpServerManager;
	}

	@Override
	public void initialize() throws Exception {
	}

	@Override
	public void destroy() throws Exception {
	}
}
